package com.heima.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

public class ConsumerQuickStart {
    public static void main(String[] args) {

        //2. 根据idea的提示配置kafka
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "42.193.102.62:9092");
        //配置分组-每一个消费者必须要配置的
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "itcast1");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");

        //关闭自动提交
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);

        //1. 创建消费者的核心对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);

        //3. 让消费者订阅一个或者多个主题
        consumer.subscribe(Collections.singletonList( "hot.article.score.out.topic"));

        //4. 从主题中循环拉取消息
        try {
            while(true){
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
                for (ConsumerRecord<String, String> record : records) {
                    System.out.println(record.key() + " : " + record.value());

                    /*//同步提交
                    consumer.commitSync();*/
                }

                // 异步提交
                /*consumer.commitAsync(new OffsetCommitCallback(){
                    @Override
                    public void onComplete(Map<TopicPartition, OffsetAndMetadata> offsets, Exception e) {
                        if(null != e){
                            e.printStackTrace();
                        }
                    }
                });*/

                consumer.commitAsync(); // 异步提交

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            consumer.commitSync(); // 同步的提交
            consumer.close();
        }
    }
}
